import Vue from 'vue'
import axios from 'axios'
import message from 'ant-design-vue/es/message'
import {
	Modal
} from 'ant-design-vue'
import router from '@/router'
import store from '@/store'
import {
	VueAxios
} from './axios'
import {
	setToken,

} from '@/api/index.js'
// message的基础配置
message.config({
	duration: 3, // 提示时常单位为s
	top: '24px', // 距离顶部的位置
	maxCount: 1 // 最多显示提示信息条数(后面的会替换前面的提示)
})
let whiteList = ['user/dictitem/getlist', 'device/productproperty/platList', 'notifier/notify-template/query',
	'device/productevent/getByProductId', 'notifier/notify/query'
]
//不需要修改sys的api
let noeditApi = {
	login: '/sys/user/login',
	logout: 'sys/user/logout', //退出登录
	getUserInfo: 'sys/user/info',
	refreshToken: 'sys/user/refresh', //刷新token
	uploadFile: 'sys/upload', //文件上传返回url
	previewFile: '/sys/preview', //图片-视频预览
	getMd5PassIsNull: '/sys/user/getMd5PassIsNull', //获取用户是否有md5密码
}
// import {
// 	baseURL
// } from './base'
axios.defaults.withCredentials = true;
// 创建 axios 实例
// 
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // api base_url
	timeout: 20000 * 3 // 请求超时时间
})

let pending = []; //声明一个数组用于存储每个ajax请求的取消函数和ajax标识
let cancelToken = axios.CancelToken; //取消接口请求
let removePending = (config) => {
	for (let p in pending) {
		if (pending[p].u === config.url + '&' + config.method) { //当当前请求在数组中存在时执行函数体
			pending[p].f(); //执行取消操作
			pending.splice(p, 1); //把这条记录从数组中移除
		}
	}
}
const err = (error) => {
	console.log(error)
	if (error.message && error.message.includes('timeout')) { // 判断请求异常信息中是否含有超时timeout字符串
		message.error('请求超时了');
	}
	if (error.response) {
		message.error(error.response.data.msg ? error.response.data.msg : '发生错误了！');
	}
	// if(error.error==invalid_token)
	return Promise.reject(error)
};
// 是否正在刷新的标记
let isRefreshing = false;
// 重试队列，每一项将是一个待执行的函数形式
let retryRequests = []
// request 拦截器
service.interceptors.request.use(config => {
		// let configUrl = config.url.split('?')[0];
		let configUrl = config.url;
		/* 如果机构是无线的机构，不是api常用接口，需要将地址中的sys改成syswl */
		/* 不在需要这个逻辑 */
		/*let urllist = Object.keys(noeditApi).map(key => noeditApi[key]); //不需要转换地址的接口
		if (store.state.user.orgIsWired == 1 && configUrl.indexOf('/sys/') > -1 && !urllist.some(item => configUrl
				.indexOf(item) > -1)) {
			configUrl = configUrl.replace('/sys/', '/syswl/');
			config.url = configUrl;
		}*/
		// let access_token = Vue.ls.get('access_token');
		let access_token = sessionStorage.getItem('access_token') || '';
		if (access_token && config.url && config.url.indexOf("user/login") == -1 && config.url.indexOf(
				"aliyuncs.com") == -1) {
			config.headers['Authorization'] = access_token
		}
		return config
	},
	err)

// response 拦截器
service.interceptors.response.use((response) => {
	removePending(response.config); //在一个ajax响应后再执行一下取消操作，把已经完成的请求从pending中移除
	/* 如果是流 */
	if (
		(response.headers &&
			(response.headers['content-type'] === 'application/octet-stream' || response.headers[
					'content-type'] === 'application/vnd.ms-excel,charset=utf-8' || response.headers[
					'content-type'] ===
				'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8')
		) || response.data.code == 1) {
		return response.data;
	} else if (response.data.code == 401) {
		const {
			config
		} = response
		/* 如果是退出登录，则直接返回 */
		if (window.location.href.indexOf("user/login") > -1 || config.url.indexOf("user/logout") > -1) {
			return response.data;
		}
		if (!isRefreshing) {
			isRefreshing = true
			// let refreshToken = Vue.ls.get('refresh_token');
			let refreshToken = sessionStorage.getItem('refresh_token') || '';
			if (refreshToken) {
				return setToken({
						refreshToken,
					})
					.then(res => {
						if (res) {
							// Vue.ls.set('access_token', res.data.access_token);
							// Vue.ls.set('refresh_token', res.data.refresh_token);
							/* 关闭浏览器不保存 */
							sessionStorage.setItem('access_token', res.data.access_token);
							sessionStorage.setItem('refresh_token', res.data.refresh_token);
							// 已经刷新了token，将所有队列中的请求进行重试
							retryRequests.forEach(cb => cb(res.data.access_token))
							// 重试完清空这个队列
							retryRequests = []
							//config.baseURL = ''
							config.headers['Authorization'] = res.data.access_token
							return service(config)
						}
					}).finally(() => {
						isRefreshing = false;

					});
			} else {
				// message.error('请先登录')
				store.dispatch('Logout').then(() => {
					window.location.reload()
				});
			}
		} else {
			return new Promise(resolve => {
				// 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
				retryRequests.push(token => {
					//config.baseURL = ''
					config.headers['Authorization'] = token
					resolve(service(config))
				})
			})
		}

	} else {
		/* 刷新refresh失效 */
		/**
		 * 当刷新token失效，code编码返回的是-1，其他接口报错也会有返回-1的情况
		 */
		if (response.config.url.indexOf('sys/user/refresh') > -1) {
			store.dispatch('Logout').then(() => {
				window.location.reload();
			});
			return response.data;
		}
		if (response.data.msg != 'success') {
			message.error(response.data.msg ? response.data.msg : '发生错误了！');
		}
		return response.data;

	}
}, err)

const installer = {
	vm: {},
	install(Vue) {
		Vue.use(VueAxios, service)
	}
}

export {
	installer as VueAxios,
	service as axios
}